import { HttpService, Injectable, Logger } from '@nestjs/common';
import * as moment from 'moment';
import { NewsPo } from '../news/interface/news.interface';
import { UserService } from './users/user.service';

@Injectable()
export class WechatService {
  private readonly logger = new Logger(WechatService.name);
  constructor(
    private readonly httpService: HttpService,
    private readonly userService: UserService,
  ) {}

  async announce(newsList: NewsPo[]) {
    if (!newsList.length) {
      return;
    }
    let openid = await this.userService.list();
    // from old to new
    newsList.slice(0, 5).forEach((news: NewsPo) => {
      this.httpService
        .request({
          url: 'http://localhost:3008/wechat/yq',
          params: news,
        })
        .toPromise();
      openid.map((item, index) => {
        this.announce2User(news, item.openid);
      });
    });
  }

  async announce2User(newsPo: NewsPo, openid: String, retry?: number) {
    if (typeof retry === 'undefined') {
      retry = 3;
    }
    let token = await this.userService.getToken();
    let {
      provinceName,
      infoSource,
      summary,
      sourceUrl,
      title,
      pubDate,
    } = newsPo;
    const opt = {
      touser: openid,
      template_id: '-ZBotrFWNIAq2rMS0hf5A0Opc6xp6ck4AP_jjbS2jbg',
      url: sourceUrl,
      topcolor: '#FF0000',
      data: {
        provinceName: {
          value: provinceName,
          color: '#173177',
        },
        infoSource: {
          value: infoSource,
          color: '#173177',
        },
        summary: {
          value: `#${title}#${summary}`,
          color: '#173177',
        },
        pubDate: {
          value: moment(Number(pubDate)).format('YYYY-MM-DD HH:mm:ss'),
          color: '#173177',
        },
      },
    };
    const res = await this.httpService
      .post(
        `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`,
        opt,
      )
      .toPromise();

    if (res.status !== 200) {
      this.logger.error('请求接口出错');
      throw new Error();
    }

    const {
      data: { errcode },
    } = res;
    if (errcode !== 0) {
      this.logger.error('请求接口失败');
      if (errcode === 40001 || errcode === 42001 || retry > 0) {
        this.userService.accessToken = '';
        await this.announce2User(newsPo, openid, retry - 1);
      }
      throw new Error(JSON.stringify(res.data));
    }
    this.logger.log('推送消息成功');
    this.logger.debug(res.data);
  }
}
